﻿using System;
using System.Web.Services;
using System.Data.SqlClient;

public partial class FormCallBacks : PageX
{
    public struct NodeAttr
    {
        public string title;
        public string key;
        public bool isFolder;
        public bool isLazy;
    };

    public SqlConnection OpenDB()
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString =
            "Data Source=.\\SQLEXPRESS;" +
            "AttachDbFilename=|DataDirectory|db1.mdf;" +
            "Integrated Security=True;User Instance=True";

        try
        {
            conn.Open();
            return conn;
        }
        catch (Exception ex)
        {
            return null;
        }

    }

    // 
    // Выдать список производителей
    //
    public void GetVendorList()
    {
        string uid = (string)Session["name"];

// Открываем базу данных
        SqlConnection conn = OpenDB();
        if (conn == null)
        {
            json_response(1, "Ошибка базы данных.");
            return;
        }

        SqlCommand comm = new SqlCommand();
        comm.Connection = conn;

// Получаем количество записей с учетом фильтра
        comm.CommandText = "SELECT COUNT(*) FROM vendors";

        Int32 count = (Int32)comm.ExecuteScalar();

// Пустая таблица
        if (count == 0)
        {
            conn.Close();
            conn.Dispose();
            echo("");
            return;
        }

        // Формируем запрос
        comm.CommandText = "SELECT (SELECT COUNT(*) AS cnt FROM models WHERE " +
            "(vend_id=vendors.vend_id)) AS mcount, vend_id, vend_name FROM vendors ORDER BY vend_name";

        SqlDataReader reader = comm.ExecuteReader();

        // Создаем структуру для возврата
        NodeAttr[] node = new NodeAttr[count];

        int imcount  = reader.GetOrdinal("mcount");
        int ivend_id = reader.GetOrdinal("vend_id");
        int ivend_name = reader.GetOrdinal("vend_name");

        int i = 0;
        while (reader.Read())
        {
            node[i] = new NodeAttr();
            node[i].key = reader.GetInt32(ivend_id).ToString();
            node[i].title = reader.GetString(ivend_name);
            node[i].isFolder = true;
            node[i].isLazy = ( reader.GetInt32(imcount) != 0 ) ? true : false;
            i++;
        }
        reader.Close();

        conn.Close();
        conn.Dispose();

        Response.AddHeader("Content-type", "text/script; charset=utf-8");
        echo(json_encode(node));
    }


    // 
    // Выдать список производителей
    //
    public void GetModelList(string node_id)
    {
        string vend_id = node_id;
        string uid = (string)Session["name"];

        // Открываем базу данных
        SqlConnection conn = OpenDB();
        if (conn == null)
        {
            json_response(1, "Ошибка базы данных.");
            return;
        }

        SqlCommand comm = new SqlCommand();
        comm.Connection = conn;

        // Получаем количество записей с учетом фильтра
        comm.CommandText = "SELECT COUNT(*) FROM models WHERE vend_id="+quote(vend_id);

        Int32 count = (Int32)comm.ExecuteScalar();

        // Пустая таблица
        if (count == 0)
        {
            conn.Close();
            conn.Dispose();
            echo("");
            return;
        }

        // Формируем запрос
        comm.CommandText = "SELECT * FROM models WHERE vend_id="+quote(vend_id)+" ORDER BY model_name;";

        SqlDataReader reader = comm.ExecuteReader();

        // Создаем структуру для возврата
        NodeAttr[] node = new NodeAttr[count];

        int imodel_id = reader.GetOrdinal("model_id");
        int imodel_name = reader.GetOrdinal("model_name");

        int i = 0;
        while (reader.Read())
        {
            node[i] = new NodeAttr();
            node[i].key = vend_id+"."+reader.GetInt32(imodel_id).ToString();
            node[i].title = reader.GetString(imodel_name);
            node[i].isFolder = false;
            node[i].isLazy = false;
            i++;
        }
        reader.Close();

        conn.Close();
        conn.Dispose();

        Response.AddHeader("Content-type", "text/script; charset=utf-8");
        echo(json_encode(node));
    }


} //End of class CallBacks
